package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * 规格Service
 */
@Service
@Transactional
public class SpecService {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> findSpecGroupsByCid(Long id) {
        //1.封装查询条件
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);

        QueryWrapper<SpecGroup> query = Wrappers.query(specGroup);

        //2.执行查询
        List<SpecGroup> specGroups = specGroupMapper.selectList(query);

        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }

        //3.获取结果，并返回
        return specGroups;
    }

    public List<SpecParam> findSpecParams(Long gid, Long cid, Boolean searching) {
        //1.封装查询条件
        SpecParam specParam = new SpecParam();

        if(gid!=null){
            specParam.setGroupId(gid);
        }

        if(cid!=null){
            specParam.setCid(cid);
        }

        if(searching!=null){
            specParam.setSearching(searching);
        }

        QueryWrapper<SpecParam> query = Wrappers.query(specParam);

        //2.执行查询，获取结果
        List<SpecParam> specParams = specParamMapper.selectList(query);

        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }

        //3.返回结果
        return specParams;
    }

    public List<SpecGroupDTO> findSpecGroupDtoByCid(Long id) {
        //1.查询规格组
        List<SpecGroup> specGroups = this.findSpecGroupsByCid(id);

        //2.转换为SpecGroupDTO对象
        List<SpecGroupDTO> specGroupDTOS = BeanHelper.copyWithCollection(specGroups, SpecGroupDTO.class);

        //3.遍历封装组内参数
        specGroupDTOS.forEach(specGroupDTO -> {
            List<SpecParam> specParams = this.findSpecParams(specGroupDTO.getId(), null, null);
            specGroupDTO.setParams(specParams);
        });
        return specGroupDTOS;
    }

    public List<SpecParam> findSpecParamById(Set<Long> ids){
        return  specParamMapper.selectBatchIds(ids);
    }
}
